package com.jn.glide.views;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jn.glide.R;
import com.jn.glide.base.BaseActivity;
import com.jn.glide.contract.MainContract;
import com.jn.glide.entity.EnglishEntity;
import com.jn.glide.entity.GroupEntity;
import com.jn.glide.entity.PictureEntity;
import com.jn.glide.entity.ResultEnity;
import com.jn.glide.service.ApiService;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends BaseActivity implements MainContract.IMainView, View.OnClickListener {

//    private Button mButton;
//    private TextView mText;
//    private ImageView mImage;
//    private ImageView mImage2;
//    private MainContract.IMainPresenter mPresenter;
//
//    @Override
//    public int getLayoutId() {
//        return R.layout.activity_main;
//    }
//
//    @Override
//    public void init() {
//        mPresenter = new MainPresenter(this, this);
//        mButton = findViewById(R.id.button);
//        mText = findViewById(R.id.text);
//        mImage = findViewById(R.id.image);
//        mImage2 = findViewById(R.id.image2);
//        mButton.setOnClickListener(this);
//    }
//
//    @Override
//    public void onClick(View v) {
//        int id = v.getId();
//        if (id == R.id.button) {
//            mPresenter.getData();
//        }
//    }
//
//    @Override
//    public void onHttpLoading(boolean loading) {
//
//    }
//
//    @Override
//    public void onHttpFail(String... msg) {
//
//    }
//
//    @Override
//    public void onHttpTimeout() {
//
//    }
//
//    @Override
//    public void onHttpTokenExpiration() {
//
//    }
//
//    @Override
//    public void showData(EnglishEntity english) {
//        StringBuffer sb = new StringBuffer();
//        sb.append(english.getResult().getNote()).append("\n\n");
//        sb.append(english.getResult().getContent());
//        mText.setText(sb.toString());
//        Glide.with(this)
//                .load(english.getResult().getImg())
//                //.dontAnimate() //不显示动画
//                //.placeholder(R.mipmap.loding) // 占位图
//                //.error(R.mipmap.error) //错误时显示的图
//                //.fallback(R.drawable.ic_launcher_background)//请求url为null时的占位图
//                //.circleCrop() // 圆形裁剪
//                //.centerCrop() // 居中裁剪
//                //.apply(requestOptions)
//                //.apply(RequestOptions.bitmapTransform(new BlurTransformation(20)))//模糊处理
//                //.apply(RequestOptions.bitmapTransform(new GrayscaleTransformation()))//黑白处理
//                //.override(50, 50)
//                //.transition(DrawableTransitionOptions.withCrossFade(factory))//定义 Glide 如何从占位符到新加载的图片
//                //.transform(new CircleCrop()) // 圆形
//                //.transform(new RoundedCorners(100)) //圆角
//                //.transform(new GranularRoundedCorners(20, 30, 40, 50))//四个角分别设置圆角
//                //.transform(new Rotate(90)) //旋转
//                //.transform(new BlurTransformation())//模糊处理
//                //.transform(new GrayscaleTransformation())//自定义
//                //.skipMemoryCache(true)//不使用内存缓存
//                //.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
//                .into(mImage);
//
//        Glide.with(this)
//                //.asGif()
//                //.asBitmap()
//                .load("https://p7.itc.cn/q_70/images03/20200717/1ed39c71685a4d6bbc88dbb2e2a1a0f6.gif")
//                //.load(R.drawable.ic_launcher_background)
//                .into(mImage2);
//    }
//
//    RequestOptions requestOptions = new RequestOptions()//提取出来供多个请求使用
//            .placeholder(R.mipmap.loding)
//            .error(R.mipmap.error)
//            .fallback(R.drawable.ic_launcher_foreground);
//
//
//    DrawableCrossFadeFactory factory =
//            new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build();
//
//
//    public class GrayscaleTransformation extends BitmapTransformation {
//
//        public GrayscaleTransformation() {
//            super();
//        }
//
//        @Override
//        protected Bitmap transform(@NonNull Context context, @NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
//            Bitmap.Config originalConfig = toTransform.getConfig();
//
//            // 创建一个新的Bitmap，其颜色格式与原始Bitmap相同
//            Bitmap bitmap = toTransform.copy(originalConfig, true);
//
//            // 应用灰度效果
//            ColorMatrix colorMatrix = new ColorMatrix();
//            colorMatrix.setSaturation(0);
//            ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
//            Paint paint = new Paint();
//            paint.setColorFilter(colorFilter);
//
//            // 在新的Bitmap上绘制修改后的图像
//            Bitmap mutableBitmap = bitmap.isMutable() ? bitmap : bitmap.copy(originalConfig, true);
//            Canvas canvas = new Canvas(mutableBitmap);
//            canvas.drawBitmap(toTransform, 0, 0, paint);
//
//            // 返回修改后的Bitmap
//            return mutableBitmap;
//        }
//
//        @Override
//        public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
//        }
//
//        @Override
//        public boolean equals(Object o) {
//            return false;
//        }
//
//        @Override
//        public int hashCode() {
//            return 0;
//        }
//    }
private Button mButtonFetch;
    private TextView mText;
    private ListView mListView;
    private ProgressBar progressBar;
    private EditText mEditTextUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButtonFetch = findViewById(R.id.buttonFetch);
        mText = findViewById(R.id.text);
        mListView = findViewById(R.id.listView);
        progressBar = findViewById(R.id.progressBar);
        mEditTextUrl = findViewById(R.id.editTextUrl);

        mButtonFetch.setOnClickListener(this);
    }

    @Override
    public int getLayoutId() {
        return 0;
    }

    @Override
    public void init() {

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.buttonFetch) {
            String url = mEditTextUrl.getText().toString();
            fetchData(url);
        }
    }

    private void fetchData(String url) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.oioweb.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiService apiService = retrofit.create(ApiService.class);
        Call<ResultEnity> call = apiService.getPictures(url);

        progressBar.setVisibility(View.VISIBLE);
        call.enqueue(new Callback<ResultEnity>() {
            @Override
            public void onResponse(Call<ResultEnity> call, Response<ResultEnity> response) {
                if (response.isSuccessful() && response.body() != null) {
                    List<GroupEntity> groups = response.body().getResult();
                    if (!groups.isEmpty()) {
                        ArrayAdapter<PictureEntity> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, groups.get(0).getList());
                        mListView.setAdapter(adapter);
                        mListView.setOnItemClickListener((parent, view, position, id) -> {
                            PictureEntity picture = (PictureEntity) mListView.getItemAtPosition(position);
                            Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                            intent.putExtra("IMAGE_URL", picture.getIcon());
                            startActivity(intent);
                        });
                    }
                }
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(Call<ResultEnity> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                // 可以在这里处理错误
            }
        });
    }

    @Override
    public void onHttpLoading(boolean loading) {

    }

    @Override
    public void onHttpFail(String... msg) {

    }

    @Override
    public void onHttpTimeout() {

    }

    @Override
    public void onHttpTokenExpiration() {

    }

    @Override
    public void showData(EnglishEntity entity) {

    }
}